<?php

namespace Apps\AppApi\Method\Order;
use Apps\AppApi\Method\BaseMethod;
use Apps\Common\Enum\PayState;
use Apps\Common\Models\UserOrder;
use Apps\Common\Models\UserOrderPayLog;
use PhalconPlus\Api\Common\ResultStatus;


/**
 * 设置订单支付状态
 * @package Apps\AppApi\Method\Order
 */
class SetPayState extends BaseMethod
{
    public function run()
    {
        /**
         * 验证用户权限
         */
        if(false == $this->verifyUserAuth()){
            return false;
        }
        $userId = $this->getUserAuth()->userId;
        $longId = $this->getDataItem('long_id', 0);
        $payType = $this->getDataItem('pay_type', '');
        $state = $this->getDataItem('state', null);
        $payOrderNum = $this->getDataItem('pay_order_num', null);
        if($longId == 0 || empty($state)) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR);
        }

        $payTypeValue = $this->getPayTypeNum($payType);
        if($payTypeValue <= 0) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '支付方式不支持.');
        }

        $stateValues = ['success', 'fail'];
        if(!in_array($state, $stateValues)) {
            return $this->errorLog(ResultStatus::POST_BODY_PARAM_ERROR, '状态值错误.');
        }
        $stateValue = 0;
        $logState = 0;
        switch($state) {
            case $stateValues[0]:
                $stateValue = 1;
                $logState = PayState::SYNC_SUCCESS;
                break;
            case $stateValues[1]:
                $stateValue = 0;
                $logState = PayState::SYNC_FAIL;
                break;
        }
        // 获取订单ID
        $orderInfo = UserOrder::findFirst("order_long_id=$longId AND user_id=$userId");
        if(!$orderInfo) {
            $this->setResult([
                'success' => 0,
                'message' => '长订单号不存在.'
            ]);
            return;
        }

        $orderId = $orderInfo->order_id;

        $this->savePayLog($longId, $payType, $payOrderNum, $logState);

        if($stateValue == 0) { // 支付失败，不处理
            $this->setResult([
                'success' => 1,
            ]);
            return;
        }
        if($orderInfo->order_pay_state < $stateValue) {
            if($orderInfo->order_state < $stateValue) {
                $orderInfo->order_state = $stateValue;
            }
            $orderInfo->order_pay_state = $stateValue;
            if(!$orderInfo->save()) {
                return $this->databaseErrorLog($orderInfo);
            }
        }

        // 添加支付记录
        $this->setResult([
            'success' => 1,
        ]);
    }

    private function savePayLog($orderId, $payType, $payNum, $payState)
    {
        $payLog = new UserOrderPayLog();
        $payLog->order_id = $orderId;
        $payLog->order_pay_type = $payType;
        $payLog->order_pay_number = $payNum;
        $payLog->order_pay_state = $payState;
        $payLog->order_pay_log_info = '';
        $payLog->save();
    }
}